/*
 * MapGraphique.cpp
 *
 *  Created on: 14 f�vr. 2013
 *      Author: Aurel
 */

#include "display/game/MapGraphique.hpp"

MapGraphique::MapGraphique(Map* p_map) : Observer(), m_map(p_map), m_cache(0), m_spriteCache(0) {
	m_image = new sf::Image;
	if (!m_image->LoadFromFile("sprites/tiles.png"))
		Debug::printTrace(Debug::critical, "display/game/MapGraphique.constructor", "Unable to load the picture");

	this->GenerateCacheMap();
}

MapGraphique::~MapGraphique(){
	//delete m_image;
	delete m_cache;
	delete m_spriteCache;
}
/**
 * Draw the map tiles
 */
void MapGraphique::draw(sf::RenderWindow* window)
{
	window->Draw(*m_spriteCache);
}
/**
 * Generate the cache of the map (optimization)
 */
void MapGraphique::GenerateCacheMap()
{
	int l_width 	= this->m_map->GetMapWidth();
	int l_height 	= this->m_map->GetMapHeight();
	int l_tileSize	= this->m_map->GetTileSize();

	m_cache 		= new sf::Image(l_width*l_tileSize,l_height*l_tileSize);
	m_spriteCache  	= new sf::Sprite();

	for(int x=0 ; x<l_width; x++)
	{
		for(int y=0 ; y<l_height; y++)
		{
			switch (this->m_map->GetTile(x, y)) {
				case Map::Wall:
					m_cache->Copy(*m_image,x*l_tileSize, y*l_tileSize, sf::IntRect(32*1,32*7,32*2,32*8), false);
					break;
				default:
					m_cache->Copy(*m_image,x*l_tileSize, y*l_tileSize, sf::IntRect(32*8,32*25,32*9,32*26), false);
					break;
			}

		}
	}

	m_cache->Bind();
	m_cache->SetSmooth(false);

	delete m_image;

	m_spriteCache->SetImage(*m_cache);
}
/**
 * not implemented
 */
void MapGraphique::Notify(int code, void* parameter)
{

}
